package com.tss.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CorsFilter implements Filter {
	
	private boolean isOpen = false ;

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse resp = (HttpServletResponse) response ;
		
		HttpServletRequest req = (HttpServletRequest) request ;
		
		//开启跨域访问
		if(isOpen){
			resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
			resp.setHeader("Access-Control-Allow-Credentials","true");
			resp.setHeader("P3P","CP=CAO PSA OUR");
            if(((HttpServletRequest) resp).getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(req.getMethod())) {
            	resp.addHeader("Access-Control-Allow-Methods", "GET,TRACE,OPTIONS");
            	resp.addHeader("Access-Control-Allow-Headers", "Content-Type,Origin,Accept");
            	resp.addHeader("Access-Control-Max-Age", "120");
            }
		}
		
		
		
		chain.doFilter(request, resp);
	}

	@Override
	public void destroy() {
		
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		this.isOpen =Boolean.valueOf( arg0.getInitParameter("isOpen"));
	}

	

}